package com.demo.config.sharding.algorithm;


import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.Properties;


/**
 * 按月分片算法
 *
 * @author airtrioa
 * @date 2021/4/30
 */
@Slf4j
@Configuration
public class ShardingAlgorithmDB implements StandardShardingAlgorithm<LocalDateTime> {

    /**
     * 精准分片
     * @param availableTargetNames available data sources or table names
     * @param shardingValue sharding value
     * @return
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<LocalDateTime> shardingValue) {

        log.info("[分库算法开始]");
        // 真实节点
        availableTargetNames.stream().forEach((item) -> {
            log.info("[存在的库名<{}>]", item);
        });

        log.info("[表名<{}> 列名<{}>]", shardingValue.getLogicTableName(), shardingValue.getColumnName());

        //精确分片
        log.info("[分库列的值<{}>]", shardingValue.getValue());

//        long orderId = shardingValue.getValue();
//
//        // 效果等同于 orderId % 2
//        long db_index = orderId & 1;

        for (String each : availableTargetNames) {
            log.info("[分库列的值<{}>]", shardingValue.getValue());
            if (each.equals("db0")) {
                return "db0";
            }
        }

        throw new IllegalArgumentException();
    }

    /**
     * 范围分片
     * @param availableTargetNames available data sources or table names
     * @param shardingValue sharding value
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<LocalDateTime> shardingValue) {
        return availableTargetNames;
    }


    @Override
    public void init() {

    }

    @Override
//    public String getType() {
//        return ShardingConstants.MONTH_SHARD;
//    }
    public String getType() {
        return "COMMON_SHARD";
    }


}

